home *** CD-ROM | disk | FTP | other *** search
/ Nebula 1 / Nebula One.iso / Graphics / Plotting / aa_Intel_Only / Gnuplot / GnuplotSource / contour.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-06-12  |  41.4 KB  |  1,273 lines

  1. #ifndef lint
  2. static char *RCSid = "$Id: contour.c%v 3.38.2.119 1993/04/26 00:02:13 woo Exp woo $";
  3. #endif
  4.  
  5.  
  6. /* GNUPLOT - contour.c */
  7. /*
  8.  * Copyright (C) 1986 - 1993   Thomas Williams, Colin Kelley
  9.  *
  10.  * Permission to use, copy, and distribute this software and its
  11.  * documentation for any purpose with or without fee is hereby granted, 
  12.  * provided that the above copyright notice appear in all copies and 
  13.  * that both that copyright notice and this permission notice appear 
  14.  * in supporting documentation.
  15.  *
  16.  * Permission to modify the software is granted, but not the right to
  17.  * distribute the modified code.  Modifications are to be distributed 
  18.  * as patches to released version.
  19.  *  
  20.  * This software is provided "as is" without express or implied warranty.
  21.  * 
  22.  *
  23.  * AUTHORS
  24.  * 
  25.  *   Original Software:
  26.  *       Gershon Elber
  27.  * 
  28.  * Send your comments or suggestions to 
  29.  *  info-gnuplot@dartmouth.edu.
  30.  * This is a mailing list; to join it send a note to 
  31.  *  info-gnuplot-request@dartmouth.edu.  
  32.  * Send bug reports to
  33.  *  bug-gnuplot@dartmouth.edu.
  34.  */
  35.  
  36. #include <stdio.h>
  37. #include "plot.h"
  38.  
  39. #define DEFAULT_NUM_OF_ZLEVELS  10  /* Some dflt values (setable via flags). */
  40. #define DEFAULT_NUM_APPROX_PTS  5
  41. #define DEFAULT_BSPLINE_ORDER  3
  42. #define MAX_NUM_OF_ZLEVELS      100 /* Some max. values (setable via flags). */
  43. #define MAX_NUM_APPROX_PTS      100
  44. #define MAX_BSPLINE_ORDER      10
  45.  
  46. #define INTERP_NOTHING   0            /* Kind of interpolations on contours. */
  47. #define INTERP_CUBIC     1                           /* Cubic spline interp. */
  48. #define APPROX_BSPLINE   2                         /* Bspline interpolation. */
  49.  
  50. #define LEVELS_AUTO            0        /* How contour levels are set */
  51. #define LEVELS_INCREMENTAL    1        /* user specified start & incremnet */
  52. #define LEVELS_DISCRETE        2        /* user specified discrete levels */
  53. #define ACTIVE   1                    /* Status of edges at certain Z level. */
  54. #define INACTIVE 2
  55.  
  56. #define OPEN_CONTOUR     1                                 /* Contour kinds. */
  57. #define CLOSED_CONTOUR   2
  58.  
  59. #define EPSILON  1e-5              /* Used to decide if two float are equal. */
  60. #define INFINITY 1e10
  61.  
  62. #ifndef TRUE
  63. #define TRUE     -1
  64. #define FALSE    0
  65. #endif
  66.  
  67. #define DEFAULT_NUM_CONTOURS    10
  68. #define MAX_POINTS_PER_CNTR     100
  69. #define SHIFT_Z_EPSILON        0.000301060 /* Dec. change of poly bndry hit.*/
  70.  
  71. #define abs(x)  ((x) > 0 ? (x) : (-(x)))
  72. #define sqr(x)  ((x) * (x))
  73.  
  74. #ifndef AMIGA_AC_5
  75. extern double sqrt();
  76. #endif /* not AMIGA_AC_5 */
  77. typedef double tri_diag[3];         /* Used to allocate the tri-diag matrix. */
  78. typedef double table_entry[4];           /* Cubic spline interpolation 4 coef. */
  79.  
  80. struct vrtx_struct {
  81.     double X, Y, Z;                       /* The coordinates of this vertex. */
  82.     struct vrtx_struct *next;                             /* To chain lists. */
  83. };
  84.  
  85. struct edge_struct {
  86.     struct poly_struct *poly[2];   /* Each edge belongs to up to 2 polygons. */
  87.     struct vrtx_struct *vertex[2]; /* The two extreme points of this vertex. */
  88.     struct edge_struct *next;                             /* To chain lists. */
  89.     int status, /* Status flag to mark edges in scanning at certain Z level. */
  90.     boundary;                   /* True if this edge is on the boundary. */
  91. };
  92.  
  93. struct poly_struct {
  94.     struct edge_struct *edge[3];           /* As we do triangolation here... */
  95.     struct poly_struct *next;                             /* To chain lists. */
  96. };
  97.  
  98. struct cntr_struct {           /* Contours are saved using this struct list. */
  99.     double X, Y;                          /* The coordinates of this vertex. */
  100.     struct cntr_struct *next;                             /* To chain lists. */
  101. };
  102.  
  103. static int test_boundary;    /* If TRUE look for contours on boundary first. */
  104. static struct gnuplot_contours *contour_list = NULL;
  105. static double crnt_cntr[MAX_POINTS_PER_CNTR * 2];
  106. static int crnt_cntr_pt_index = 0;
  107. static double contour_level = 0.0;
  108. static table_entry *hermit_table = NULL;    /* Hold hermite table constants. */
  109. static int num_of_z_levels = DEFAULT_NUM_OF_ZLEVELS;  /* # Z contour levels. */
  110. static int num_approx_pts = DEFAULT_NUM_APPROX_PTS;/* # pts per approx/inter.*/
  111. static int bspline_order = DEFAULT_BSPLINE_ORDER;   /* Bspline order to use. */
  112. static int interp_kind = INTERP_NOTHING;  /* Linear, Cubic interp., Bspline. */
  113. static int levels_kind = LEVELS_AUTO;  /* auto, incremental, discrete */
  114.  
  115.  
  116. static void gen_contours();
  117. static int update_all_edges();
  118. static struct cntr_struct *gen_one_contour();
  119. static struct cntr_struct *trace_contour();
  120. static struct cntr_struct *update_cntr_pt();
  121. static int fuzzy_equal();
  122. static void gen_triangle();
  123. static struct vrtx_struct *gen_vertices();
  124. static struct edge_struct *gen_edges_middle();
  125. static struct edge_struct *gen_edges();
  126. static struct poly_struct *gen_polys();
  127. static void free_contour();
  128. static void put_contour();
  129. static put_contour_nothing();
  130. static put_contour_cubic();
  131. static put_contour_bspline();
  132. static calc_tangent();
  133. static int count_contour();
  134. static complete_spline_interp();
  135. static calc_hermit_table();
  136. static hermit_interp();
  137. static prepare_spline_interp();
  138. static int solve_tri_diag();
  139. static gen_bspline_approx();
  140. static double fetch_knot();
  141. static eval_bspline();
  142.  
  143. /*
  144.  * Entry routine to this whole set of contouring module.
  145.  */
  146. struct gnuplot_contours *contour(num_isolines, iso_lines,
  147.                  ZLevels, approx_pts, int_kind, order1,
  148.                  levels_kind, levels_list)
  149. int num_isolines;
  150. struct iso_curve *iso_lines;
  151. int ZLevels, approx_pts, int_kind, order1;
  152. int levels_kind;
  153. double *levels_list;
  154. {
  155.     int i;
  156.     struct poly_struct *p_polys, *p_poly;
  157.     struct edge_struct *p_edges, *p_edge;
  158.     struct vrtx_struct *p_vrts, *p_vrtx;
  159.     double x_min, y_min, z_min, x_max, y_max, z_max, z, dz;
  160.      struct gnuplot_contours *save_contour_list;
  161.  
  162.     num_of_z_levels = ZLevels;
  163.     num_approx_pts = approx_pts;
  164.     bspline_order = order1 - 1;
  165.     interp_kind = int_kind;
  166.  
  167.     contour_list = NULL;
  168.  
  169.     if (interp_kind == INTERP_CUBIC) calc_hermit_table();
  170.  
  171.     gen_triangle(num_isolines, iso_lines, &p_polys, &p_edges, &p_vrts,
  172.         &x_min, &y_min, &z_min, &x_max, &y_max, &z_max);
  173.     crnt_cntr_pt_index = 0;
  174.  
  175.     dz = (z_max - z_min) / (num_of_z_levels + 1);
  176.     z = z_min;
  177.     for (i = 0; i < num_of_z_levels; i++) {
  178.         switch(levels_kind) {
  179.             case LEVELS_AUTO:
  180.                 /* Step from z_min+dz upto z_max-dz in num_of_z_levels times. */
  181.                 z += dz;
  182.                 break;
  183.             case LEVELS_INCREMENTAL:
  184.                 z = levels_list[0] + i * levels_list[1];
  185.                 break;
  186.             case LEVELS_DISCRETE:
  187.                 z = levels_list[i];
  188.                 break;
  189.         }
  190.         contour_level = z;
  191.          save_contour_list = contour_list;
  192.         gen_contours(p_edges, z + dz * SHIFT_Z_EPSILON, x_min, x_max,
  193.                                 y_min, y_max);
  194.          if(contour_list != save_contour_list) {
  195.              contour_list->isNewLevel = 1;
  196.              sprintf(contour_list->label, "%8.3g", z);
  197.          }
  198.     }
  199.  
  200.     /* Free all contouring related temporary data. */
  201.     while (p_polys) {
  202.     p_poly = p_polys -> next;
  203.     free (p_polys);
  204.     p_polys = p_poly;
  205.     }
  206.     while (p_edges) {
  207.     p_edge = p_edges -> next;
  208.     free (p_edges);
  209.     p_edges = p_edge;
  210.     }
  211.     while (p_vrts) {
  212.     p_vrtx = p_vrts -> next;
  213.     free (p_vrts);
  214.     p_vrts = p_vrtx;
  215.     }
  216.  
  217.     if (interp_kind == INTERP_CUBIC) free(hermit_table);
  218.  
  219.     return contour_list;
  220. }
  221.  
  222. /*
  223.  * Adds another point to the currently build contour.
  224.  */
  225. add_cntr_point(x, y)
  226. double x, y;
  227. {
  228.     int index;
  229.  
  230.     if (crnt_cntr_pt_index >= MAX_POINTS_PER_CNTR-1) {
  231.     index = crnt_cntr_pt_index - 1;
  232.     end_crnt_cntr();
  233.     crnt_cntr[0] = crnt_cntr[index * 2];
  234.     crnt_cntr[1] = crnt_cntr[index * 2 + 1];
  235.     crnt_cntr_pt_index = 1; /* Keep the last point as first of this one. */
  236.     }
  237.     crnt_cntr[crnt_cntr_pt_index * 2] = x;
  238.     crnt_cntr[crnt_cntr_pt_index * 2 + 1] = y;
  239.     crnt_cntr_pt_index++;
  240. }
  241.  
  242. /*
  243.  * Done with current contour - create gnuplot data structure for it.
  244.  */
  245. end_crnt_cntr()
  246. {
  247.     int i;
  248.     struct gnuplot_contours *cntr = (struct gnuplot_contours *)
  249.                     alloc((unsigned long)sizeof(struct gnuplot_contours),
  250.                           "gnuplot_contour");
  251.  
  252.     cntr->coords = (struct coordinate GPHUGE *) gpfaralloc((unsigned long)sizeof(struct coordinate) *
  253.                               ( unsigned long)crnt_cntr_pt_index,
  254.                            "contour coords");
  255.     for (i=0; i<crnt_cntr_pt_index; i++) {
  256.     cntr->coords[i].x = crnt_cntr[i * 2];
  257.     cntr->coords[i].y = crnt_cntr[i * 2 + 1];
  258.     cntr->coords[i].z = contour_level;
  259.     }
  260.     cntr->num_pts = crnt_cntr_pt_index;
  261.  
  262.     cntr->next = contour_list;
  263.     contour_list = cntr;
  264.      contour_list->isNewLevel = 0;
  265.  
  266.     crnt_cntr_pt_index = 0;
  267. }
  268.  
  269. /*
  270.  * Generates all contours by tracing the intersecting triangles.
  271.  */
  272. static void gen_contours(p_edges, z_level, x_min, x_max, y_min, y_max)
  273. struct edge_struct *p_edges;
  274. double z_level, x_min, x_max, y_min, y_max;
  275. {
  276.     int num_active,                        /* Number of edges marked ACTIVE. */
  277.     contour_kind;                /* One of OPEN_CONTOUR, CLOSED_CONTOUR. */
  278.     struct cntr_struct *p_cntr;
  279.  
  280.     num_active = update_all_edges(p_edges, z_level);           /* Do pass 1. */
  281.  
  282.     test_boundary = TRUE;        /* Start to look for contour on boundaries. */
  283.  
  284.     while (num_active > 0) {                                   /* Do Pass 2. */
  285.         /* Generate One contour (and update MumActive as needed): */
  286.     p_cntr = gen_one_contour(p_edges, z_level, &contour_kind, &num_active);
  287.     put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max,
  288.                   contour_kind); /* Emit it in requested format. */
  289.     }
  290. }
  291.  
  292. /*
  293.  * Does pass 1, or marks the edges which are active (crosses this z_level)
  294.  * as ACTIVE, and the others as INACTIVE:
  295.  * Returns number of active edges (marked ACTIVE).
  296.  */
  297. static int update_all_edges(p_edges, z_level)
  298. struct edge_struct *p_edges;
  299. double z_level;
  300. {
  301.     int count = 0;
  302.  
  303.     while (p_edges) {
  304.     if (((p_edges -> vertex[0] -> Z >= z_level) &&
  305.          (p_edges -> vertex[1] -> Z <= z_level)) ||
  306.         ((p_edges -> vertex[1] -> Z >= z_level) &&
  307.          (p_edges -> vertex[0] -> Z <= z_level))) {
  308.         p_edges -> status = ACTIVE;
  309.         count++;
  310.     }
  311.     else p_edges -> status = INACTIVE;
  312.     p_edges = p_edges -> next;
  313.     }
  314.  
  315.     return count;
  316. }
  317.  
  318. /*
  319.  * Does pass 2, or find one complete contour out of the triangolation data base:
  320.  * Returns a pointer to the contour (as linked list), contour_kind is set to
  321.  * one of OPEN_CONTOUR, CLOSED_CONTOUR, and num_active is updated.
  322.  */
  323. static struct cntr_struct *gen_one_contour(p_edges, z_level, contour_kind,
  324.                                 num_active)
  325. struct edge_struct *p_edges;
  326. double z_level;
  327. int *contour_kind, *num_active;
  328. {
  329.     struct edge_struct *pe_temp;
  330.  
  331.     if (test_boundary) {    /* Look for something to start with on boundary: */
  332.     pe_temp = p_edges;
  333.     while (pe_temp) {
  334.         if ((pe_temp -> status == ACTIVE) && (pe_temp -> boundary)) break;
  335.         pe_temp = pe_temp -> next;
  336.     }
  337.     if (!pe_temp) test_boundary = FALSE;/* No more contours on boundary. */
  338.     else {
  339.         *contour_kind = OPEN_CONTOUR;
  340.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  341.     }
  342.     }
  343.  
  344.     if (!test_boundary) {        /* Look for something to start with inside: */
  345.     pe_temp = p_edges;
  346.     while (pe_temp) {
  347.         if ((pe_temp -> status == ACTIVE) && (!(pe_temp -> boundary)))
  348.         break;
  349.         pe_temp = pe_temp -> next;
  350.     }
  351.     if (!pe_temp) {
  352.         *num_active = 0;
  353.         return NULL;
  354.     }
  355.     else {
  356.         *contour_kind = CLOSED_CONTOUR;
  357.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  358.     }
  359.     }
  360.     return NULL;             /* We should never be here, but lint... */
  361. }
  362.  
  363. /*
  364.  * Search the data base along a contour starts at the edge pe_start until
  365.  * a boundary edge is detected or until we close the loop back to pe_start.
  366.  * Returns a linked list of all the points on the contour
  367.  * Also decreases num_active by the number of points on contour.
  368.  */
  369. static struct cntr_struct *trace_contour(pe_start, z_level, num_active,
  370.                                 contour_kind)
  371. struct edge_struct *pe_start;
  372. double z_level;
  373. int *num_active, contour_kind;
  374. {
  375.     int i, in_middle;       /* If TRUE the z_level is in the middle of edge. */
  376.     struct cntr_struct *p_cntr, *pc_tail;
  377.     struct edge_struct *p_edge = pe_start, *p_next_edge;
  378.     struct poly_struct *p_poly, *PLastpoly = NULL;
  379.  
  380.     /* Generate the header of the contour - the point on pe_start. */
  381.     if (contour_kind == OPEN_CONTOUR) pe_start -> status = INACTIVE;
  382.     (*num_active)--;
  383.     p_cntr = pc_tail = update_cntr_pt(pe_start, z_level, &in_middle);
  384.     if (!in_middle) {
  385.     return NULL;
  386.     }
  387.  
  388.     do {
  389.     /* Find polygon to continue (Not where we came from - PLastpoly): */
  390.     if (p_edge -> poly[0] == PLastpoly) p_poly = p_edge -> poly[1];
  391.     else p_poly = p_edge -> poly[0];
  392.     p_next_edge = NULL;          /* In case of error, remains NULL. */
  393.     for (i=0; i<3; i++)              /* Test the 3 edges of the polygon: */
  394.         if (p_poly -> edge[i] != p_edge)
  395.             if (p_poly -> edge[i] -> status == ACTIVE)
  396.             p_next_edge = p_poly -> edge[i];
  397.     if (!p_next_edge) {
  398.         pc_tail -> next = NULL;
  399.         free_contour(p_cntr);
  400.         return NULL;
  401.     }
  402.     p_edge = p_next_edge;
  403.     PLastpoly = p_poly;
  404.     p_edge -> status = INACTIVE;
  405.     (*num_active)--;
  406.     pc_tail -> next = update_cntr_pt(p_edge, z_level, &in_middle);
  407.     if (!in_middle) {
  408.         pc_tail -> next = NULL;
  409.         free_contour(p_cntr);
  410.         return NULL;
  411.     }
  412.         pc_tail = pc_tail -> next;
  413.     }
  414.     while ((pe_start != p_edge) && (!p_edge -> boundary));
  415.     pc_tail -> next = NULL;
  416.  
  417.     return p_cntr;
  418. }
  419.  
  420. /*
  421.  * Allocates one contour location and update it to to correct position
  422.  * according to z_level and edge p_edge. if z_level is found to be at
  423.  * one of the extreme points nothing is allocated (NULL is returned)
  424.  * and in_middle is set to FALSE.
  425.  */
  426. static struct cntr_struct *update_cntr_pt(p_edge, z_level, in_middle)
  427. struct edge_struct *p_edge;
  428. double z_level;
  429. int *in_middle;
  430. {
  431.     double t;
  432.     struct cntr_struct *p_cntr;
  433.  
  434.     t = (z_level - p_edge -> vertex[0] -> Z) /
  435.     (p_edge -> vertex[1] -> Z - p_edge -> vertex[0] -> Z);
  436.  
  437.     if (fuzzy_equal(t, 1.0) || fuzzy_equal(t, 0.0)) {
  438.         *in_middle = FALSE;
  439.         return NULL;
  440.     }
  441.     else {
  442.     *in_middle = TRUE;
  443.     p_cntr = (struct cntr_struct *) alloc((unsigned long)sizeof(struct cntr_struct),
  444.                             "contour cntr_struct");
  445.     p_cntr -> X = p_edge -> vertex[1] -> X * t +
  446.              p_edge -> vertex[0] -> X * (1-t);
  447.     p_cntr -> Y = p_edge -> vertex[1] -> Y * t +
  448.              p_edge -> vertex[0] -> Y * (1-t);
  449.     return p_cntr;
  450.     }
  451. }
  452.  
  453. /*
  454.  * Simple routine to decide if two real values are equal by simply
  455.  * calculating the relative/absolute error between them (< EPSILON).
  456.  */
  457. static int fuzzy_equal(x, y)
  458. double x, y;
  459. {
  460.     if (abs(x) > EPSILON)            /* Calculate relative error: */
  461.         return (abs((x - y) / x) < EPSILON);
  462.     else                    /* Calculate absolute error: */
  463.     return (abs(x - y) < EPSILON);
  464. }
  465.  
  466. /*
  467.  * Generate the triangles.
  468.  * Returns the lists (vrtxs edges & polys) via pointers to their heads.
  469.  */
  470. static void gen_triangle(num_isolines, iso_lines, p_polys, p_edges,
  471.     p_vrts, x_min, y_min, z_min, x_max, y_max, z_max)
  472. int num_isolines;
  473. struct iso_curve *iso_lines;
  474. struct poly_struct **p_polys;
  475. struct edge_struct **p_edges;
  476. struct vrtx_struct **p_vrts;
  477. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  478. {
  479.     int i, grid_x_max = iso_lines->p_count;
  480.     struct vrtx_struct *p_vrtx1, *p_vrtx2, *pv_temp;
  481.     struct edge_struct *p_edge1, *p_edge2, *pe_tail1, *pe_tail2, *pe_temp,
  482.               *p_edge_middle, *pe_m_tail;
  483.     struct poly_struct *p_poly, *pp_tail;
  484.  
  485.     *p_polys = NULL;
  486.     *p_edges = NULL;
  487.     *p_vrts = NULL;
  488.     *z_min = INFINITY;
  489.     *y_min = INFINITY;
  490.     *x_min = INFINITY;
  491.     *z_max = -INFINITY;
  492.     *y_max = -INFINITY;
  493.     *x_max = -INFINITY;
  494.  
  495.     /* Read 1st row. */
  496.     p_vrtx1 = gen_vertices(grid_x_max, iso_lines->points,
  497.                x_min, y_min, z_min, x_max, y_max, z_max);
  498.     *p_vrts = p_vrtx1;
  499.     /* Gen. its edges.*/
  500.     pe_temp = p_edge1 = gen_edges(grid_x_max, p_vrtx1, &pe_tail1);
  501.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  502.     pe_temp -> poly[1] = NULL;
  503.     pe_temp = pe_temp -> next;
  504.     }
  505.     for (i = 1; i < num_isolines; i++) { /* Read next column and gen. polys. */
  506.     iso_lines = iso_lines->next;
  507.         /* Get row into list. */
  508.         p_vrtx2 = gen_vertices(grid_x_max, iso_lines->points,
  509.                    x_min, y_min, z_min, x_max, y_max, z_max);
  510.         /* Generate its edges. */
  511.         p_edge2 = gen_edges(grid_x_max, p_vrtx2, &pe_tail2);
  512.     /* Generate edges from one vertex list to the other one: */
  513.     p_edge_middle = gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  514.                                  &pe_m_tail);
  515.  
  516.     /* Now we can generate the polygons themselves (triangles). */
  517.     p_poly = gen_polys(grid_x_max, p_edge1, p_edge_middle, p_edge2,
  518.                                  &pp_tail);
  519.         pe_tail1 -> next = (*p_edges);      /* Chain new edges to main list. */
  520.         pe_m_tail -> next = p_edge1;
  521.     *p_edges = p_edge_middle;
  522.     pe_tail1 = pe_tail2;
  523.     p_edge1 = p_edge2;
  524.  
  525.     pv_temp = p_vrtx2;
  526.     while (pv_temp -> next) pv_temp = pv_temp -> next;
  527.     pv_temp -> next = *p_vrts;
  528.     *p_vrts = p_vrtx1 = p_vrtx2;
  529.  
  530.         pp_tail -> next = (*p_polys);       /* Chain new polys to main list. */
  531.     *p_polys = p_poly;
  532.     }
  533.  
  534.     pe_temp = p_edge1;
  535.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  536.     pe_temp -> poly[0] = NULL;
  537.     pe_temp = pe_temp -> next;
  538.     }
  539.  
  540.     pe_tail1 -> next = (*p_edges);    /* Chain last edges list to main list. */
  541.     *p_edges = p_edge1;
  542.  
  543.     /* Update the boundary flag, saved in each edge, and update indexes: */
  544.     pe_temp = (*p_edges);
  545.     i = 1;
  546.  
  547.     while (pe_temp) {
  548.     pe_temp -> boundary = (!(pe_temp -> poly[0])) ||
  549.                   (!(pe_temp -> poly[1]));
  550.     pe_temp = pe_temp -> next;
  551.     }
  552. }
  553.  
  554. /*
  555.  * Handles grid_x_max 3D points (One row) and generate linked list for them.
  556.  */
  557. static struct vrtx_struct *gen_vertices(grid_x_max, points,
  558.                       x_min, y_min, z_min, x_max, y_max, z_max)
  559. int grid_x_max;
  560. struct coordinate GPHUGE *points;
  561. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  562. {
  563.     int i;
  564.     struct vrtx_struct *p_vrtx, *pv_tail, *pv_temp;
  565.  
  566.     for (i=0; i<grid_x_max; i++) {/* Get a point and generate the structure. */
  567.         pv_temp = (struct vrtx_struct *) alloc((unsigned long)sizeof(struct vrtx_struct),
  568.                         "contour vertex");
  569.     pv_temp -> X = points[i].x;
  570.     pv_temp -> Y = points[i].y;
  571.     pv_temp -> Z = points[i].z;
  572.  
  573.     if (pv_temp -> X > *x_max) *x_max = pv_temp -> X; /* Update min/max. */
  574.     if (pv_temp -> Y > *y_max) *y_max = pv_temp -> Y;
  575.     if (pv_temp -> Z > *z_max) *z_max = pv_temp -> Z;
  576.     if (pv_temp -> X < *x_min) *x_min = pv_temp -> X;
  577.     if (pv_temp -> Y < *y_min) *y_min = pv_temp -> Y;
  578.     if (pv_temp -> Z < *z_min) *z_min = pv_temp -> Z;
  579.  
  580.     if (i == 0)                              /* First vertex in row: */
  581.         p_vrtx = pv_tail = pv_temp;
  582.     else {
  583.         pv_tail -> next = pv_temp;   /* Stick new record as last one. */
  584.         pv_tail = pv_tail -> next;    /* And continue to last record. */
  585.     }
  586.     }
  587.     pv_tail -> next = NULL;
  588.  
  589.     return p_vrtx;
  590. }
  591.  
  592. /*
  593.  * Combines N vertices in pair to form N-1 edges.
  594.  * Returns pointer to the edge list (pe_tail will point on last edge in list).
  595.  */
  596. static struct edge_struct *gen_edges(grid_x_max, p_vrtx, pe_tail)
  597. int grid_x_max;
  598. struct vrtx_struct *p_vrtx;
  599. struct edge_struct **pe_tail;
  600. {
  601.     int i;
  602.     struct edge_struct *p_edge, *pe_temp;
  603.  
  604.     for (i=0; i<grid_x_max-1; i++) {         /* Generate grid_x_max-1 edges: */
  605.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  606.                         "contour edge");
  607.     pe_temp -> vertex[0] = p_vrtx;              /* First vertex of edge. */
  608.     p_vrtx = p_vrtx -> next;                     /* Skip to next vertex. */
  609.     pe_temp -> vertex[1] = p_vrtx;             /* Second vertex of edge. */
  610.         if (i == 0)                                    /* First edge in row: */
  611.         p_edge = (*pe_tail) = pe_temp;
  612.     else {
  613.         (*pe_tail) -> next = pe_temp;   /* Stick new record as last one. */
  614.         *pe_tail = (*pe_tail) -> next;   /* And continue to last record. */
  615.      }
  616.     }
  617.     (*pe_tail) -> next = NULL;
  618.  
  619.     return p_edge;
  620. }
  621.  
  622. /*
  623.  * Combines 2 lists of N vertices each into edge list:
  624.  * The dots (.) are the vertices list, and the              .  .  .  .
  625.  *  edges generated are alternations of vertical edges      |\ |\ |\ |
  626.  *  (|) and diagonal ones (\).                              | \| \| \|
  627.  *  A pointer to edge list (alternate | , \) is returned    .  .  .  .
  628.  * Note this list will have (2*grid_x_max-1) edges (pe_tail points on last
  629.  * record).
  630.  */
  631. static struct edge_struct *gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  632.                                 pe_tail)
  633. int grid_x_max;
  634. struct vrtx_struct *p_vrtx1, *p_vrtx2;
  635. struct edge_struct **pe_tail;
  636. {
  637.     int i;
  638.     struct edge_struct *p_edge, *pe_temp;
  639.  
  640.     /* Gen first (|). */
  641.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  642.                             "contour edge");
  643.     pe_temp -> vertex[0] = p_vrtx2;                 /* First vertex of edge. */
  644.     pe_temp -> vertex[1] = p_vrtx1;                /* Second vertex of edge. */
  645.     p_edge = (*pe_tail) = pe_temp;
  646.  
  647.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 edges /| for each.*/
  648.     for (i=0; i<grid_x_max-1; i++) {
  649.     /* The / edge. */
  650.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  651.                             "contour edge");
  652.     pe_temp -> vertex[0] = p_vrtx1;             /* First vertex of edge. */
  653.     pe_temp -> vertex[1] = p_vrtx2 -> next;    /* Second vertex of edge. */
  654.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  655.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  656.  
  657.     /* The | edge. */
  658.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  659.                             "contour edge");
  660.     pe_temp -> vertex[0] = p_vrtx2 -> next;     /* First vertex of edge. */
  661.     pe_temp -> vertex[1] = p_vrtx1 -> next;    /* Second vertex of edge. */
  662.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  663.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  664.  
  665.         p_vrtx1 = p_vrtx1 -> next;   /* Skip to next vertices in both lists. */
  666.         p_vrtx2 = p_vrtx2 -> next;
  667.     }
  668.     (*pe_tail) -> next = NULL;
  669.  
  670.     return p_edge;
  671. }
  672.  
  673. /*
  674.  * Combines 3 lists of edges into triangles:
  675.  * 1. p_edge1: Top horizontal edge list:        -----------------------
  676.  * 2. p_edge_middge: middle edge list:         |\  |\  |\  |\  |\  |\  |
  677.  *                                             |  \|  \|  \|  \|  \|  \|
  678.  * 3. p_edge2: Bottom horizontal edge list:     -----------------------
  679.  * Note that p_edge1/2 lists has grid_x_max-1 edges, while p_edge_middle has
  680.  * (2*grid_x_max-1) edges.
  681.  * The routine simple scans the two list    Upper 1         Lower
  682.  * and generate two triangle upper one        ----         | \
  683.  * and lower one from the lists:             0\   |2      0|   \1
  684.  * (Nums. are edges order in polys)             \ |         ----
  685.  * The routine returns a pointer to a                         2
  686.  * polygon list (pp_tail points on last polygon).          1
  687.  *                                                   -----------
  688.  * In addition, the edge lists are updated -        | \   0     |
  689.  * each edge has two pointers on the two            |   \       |
  690.  * (one active if boundary) polygons which         0|1   0\1   0|1
  691.  * uses it. These two pointer to polygons           |       \   |
  692.  * are named: poly[0], poly[1]. The diagram         |    1    \ |
  693.  * on the right show how they are used for the       -----------
  694.  * upper and lower polygons.                             0
  695.  */
  696. static struct poly_struct *gen_polys(grid_x_max, p_edge1, p_edge_middle,
  697.                             p_edge2, pp_tail)
  698. int grid_x_max;
  699. struct edge_struct *p_edge1, *p_edge_middle, *p_edge2;
  700. struct poly_struct **pp_tail;
  701. {
  702.     int i;
  703.     struct poly_struct *p_poly, *pp_temp;
  704.  
  705.     p_edge_middle -> poly[0] = NULL;                /* Its boundary! */
  706.  
  707.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 polys for each. */
  708.     for (i=0; i<grid_x_max-1; i++) {
  709.     /* The Upper. */
  710.     pp_temp = (struct poly_struct *) alloc((unsigned long)sizeof(struct poly_struct),
  711.                             "contour poly");
  712.     /* Now update polys about its edges, and edges about the polygon. */
  713.     pp_temp -> edge[0] = p_edge_middle -> next;
  714.     p_edge_middle -> next -> poly[1] = pp_temp;
  715.     pp_temp -> edge[1] = p_edge1;
  716.     p_edge1 -> poly[0] = pp_temp;
  717.     pp_temp -> edge[2] = p_edge_middle -> next -> next;
  718.     p_edge_middle -> next -> next -> poly[0] = pp_temp;
  719.     if (i == 0)                   /* Its first one in list: */
  720.         p_poly = (*pp_tail) = pp_temp;
  721.     else {
  722.         (*pp_tail) -> next = pp_temp;
  723.         *pp_tail = (*pp_tail) -> next;
  724.     }
  725.  
  726.     /* The Lower. */
  727.     pp_temp = (struct poly_struct *) alloc((unsigned long)sizeof(struct poly_struct),
  728.                             "contour poly");
  729.     /* Now update polys about its edges, and edges about the polygon. */
  730.     pp_temp -> edge[0] = p_edge_middle;
  731.     p_edge_middle -> poly[1] = pp_temp;
  732.     pp_temp -> edge[1] = p_edge_middle -> next;
  733.     p_edge_middle -> next -> poly[0] = pp_temp;
  734.     pp_temp -> edge[2] = p_edge2;
  735.     p_edge2 -> poly[1] = pp_temp;
  736.     (*pp_tail) -> next = pp_temp;
  737.     *pp_tail = (*pp_tail) -> next;
  738.  
  739.         p_edge1 = p_edge1 -> next;
  740.         p_edge2 = p_edge2 -> next;
  741.         p_edge_middle = p_edge_middle -> next -> next;
  742.     }
  743.     p_edge_middle -> poly[1] = NULL;                /* Its boundary! */
  744.     (*pp_tail) -> next = NULL;
  745.  
  746.     return p_poly;
  747. }
  748.  
  749. /*
  750.  * Calls the (hopefully) desired interpolation/approximation routine.
  751.  */
  752. static void put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max, contr_kind)
  753. struct cntr_struct *p_cntr;
  754. double z_level, x_min, x_max, y_min, y_max;
  755. int contr_kind;
  756. {
  757.     if (!p_cntr) return;            /* Nothing to do if it is empty contour. */
  758.  
  759.     switch (interp_kind) {
  760.     case INTERP_NOTHING:              /* No interpolation/approximation. */
  761.         put_contour_nothing(p_cntr);
  762.         break;
  763.     case INTERP_CUBIC:                    /* Cubic spline interpolation. */
  764.         put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  765.                                 contr_kind);
  766.         break;
  767.     case APPROX_BSPLINE:                       /* Bspline approximation. */
  768.         put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  769.                                     contr_kind);
  770.         break;
  771.     }
  772.  
  773.     free_contour(p_cntr);
  774. }
  775.  
  776. /*
  777.  * Simply puts contour coordinates in order with no interpolation or
  778.  * approximation.
  779.  */
  780. static put_contour_nothing(p_cntr)
  781. struct cntr_struct *p_cntr;
  782. {
  783.     while (p_cntr) {
  784.     add_cntr_point(p_cntr -> X, p_cntr -> Y);
  785.     p_cntr = p_cntr -> next;
  786.     }
  787.     end_crnt_cntr();
  788. }
  789.  
  790. /*
  791.  * Find Complete Cubic Spline Interpolation.
  792.  */
  793. static put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  794.                                  contr_kind)
  795. struct cntr_struct *p_cntr;
  796. double z_level, x_min, x_max, y_min, y_max;
  797. int contr_kind;
  798. {
  799.     int num_pts, i;
  800.     double tx1, ty1, tx2, ty2;                    /* Tangents at end points. */
  801.     struct cntr_struct *pc_temp;
  802.  
  803.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  804.  
  805.     if (num_pts > 2) {  /* Take into account 3 points in tangent estimation. */
  806.     calc_tangent(3, p_cntr -> X, p_cntr -> next -> X,
  807.             p_cntr -> next -> next -> X,
  808.             p_cntr -> Y, p_cntr -> next -> Y,
  809.             p_cntr -> next -> next -> Y, &tx1, &ty1);
  810.     pc_temp = p_cntr;
  811.     for (i=3; i<num_pts; i++) pc_temp = pc_temp -> next;/* Go to the end.*/
  812.     calc_tangent(3, pc_temp -> next -> next -> X,
  813.              pc_temp -> next -> X, pc_temp -> X,
  814.             pc_temp -> next -> next -> Y,
  815.             pc_temp -> next -> Y, pc_temp -> Y, &tx2, &ty2);
  816.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  817.         ty2 = (-ty2);
  818.     }
  819.     /* If following (num_pts > 1) is TRUE then exactly 2 points in contour.  */
  820.     else if (num_pts > 1) {/* Take into account 2 points in tangent estimat. */
  821.     calc_tangent(2, p_cntr -> X, p_cntr -> next -> X, 0.0,
  822.             p_cntr -> Y, p_cntr -> next -> Y, 0.0, &tx1, &ty1);
  823.     calc_tangent(2, p_cntr -> next -> X, p_cntr -> X, 0.0,
  824.             p_cntr -> next -> Y, p_cntr -> Y, 0.0, &tx2, &ty2);
  825.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  826.         ty2 = (-ty2);
  827.     }
  828.     else return(0);            /* Only one point (???) - ignore it. */
  829.  
  830.     switch (contr_kind) {
  831.     case OPEN_CONTOUR:
  832.         break;
  833.     case CLOSED_CONTOUR:
  834.         tx1 = tx2 = (tx1 + tx2) / 2.0;         /* Make tangents equal. */
  835.         ty1 = ty2 = (ty1 + ty2) / 2.0;
  836.         break;
  837.     }
  838.     complete_spline_interp(p_cntr, num_pts, 0.0, 1.0, tx1, ty1, tx2, ty2);
  839.     end_crnt_cntr();
  840. }
  841.  
  842. /*
  843.  * Find Bspline approximation for this data set.
  844.  * Uses global variable num_approx_pts to determine number of samples per
  845.  * interval, where the knot vector intervals are assumed to be uniform, and
  846.  * Global variable bspline_order for the order of Bspline to use.
  847.  */
  848. static put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  849.                                 contr_kind)
  850. struct cntr_struct *p_cntr;
  851. double z_level, x_min, x_max,  y_min, y_max;
  852. int contr_kind;
  853. {
  854.     int num_pts, order = bspline_order;
  855.  
  856.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  857.     if (num_pts < 2) return(0);     /* Can't do nothing if empty or one points! */
  858.     /* Order must be less than number of points in curve - fix it if needed. */
  859.     if (order > num_pts - 1) order = num_pts - 1;
  860.  
  861.     gen_bspline_approx(p_cntr, num_pts, order, contr_kind);
  862.     end_crnt_cntr();
  863. }
  864.  
  865. /*
  866.  * Estimate the tangents according to the n last points where n might be
  867.  * 2 or 3 (if 2 onlt x1, x2).
  868.  */
  869. static calc_tangent(n, x1, x2, x3, y1, y2, y3, tx, ty)
  870. int n;
  871. double x1, x2, x3, y1, y2, y3, *tx, *ty;
  872. {
  873.     double v1[2], v2[2], v1_magnitude, v2_magnitude;
  874.  
  875.     switch (n) {
  876.     case 2:
  877.         *tx = (x2 - x1) * 0.3;
  878.         *ty = (y2 - y1) * 0.3;
  879.         break;
  880.     case 3:
  881.         v1[0] = x2 - x1;   v1[1] = y2 - y1;
  882.         v2[0] = x3 - x2;   v2[1] = y3 - y2;
  883.         v1_magnitude = sqrt(sqr(v1[0]) + sqr(v1[1]));
  884.         v2_magnitude = sqrt(sqr(v2[0]) + sqr(v2[1]));
  885.         *tx = (v1[0] / v1_magnitude) - (v2[0] / v2_magnitude) * 0.1;
  886.         *tx *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  887.         *ty = (v1[1] / v1_magnitude) - (v2[1] / v2_magnitude) * 0.1;
  888.         *ty *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  889.         break;
  890.     default:                       /* Should not happen! */
  891.         (*ty) = 0.1;
  892.         *tx = 0.1;
  893.         break;
  894.     }
  895. }
  896.  
  897. /*
  898.  * Free all elements in the contour list.
  899.  */
  900. static void free_contour(p_cntr)
  901. struct cntr_struct *p_cntr;
  902. {
  903.     struct cntr_struct *pc_temp;
  904.  
  905.     while (p_cntr) {
  906.     pc_temp = p_cntr;
  907.     p_cntr = p_cntr -> next;
  908.     free((char *) pc_temp);
  909.     }
  910. }
  911.  
  912. /*
  913.  * Counts number of points in contour.
  914.  */
  915. static int count_contour(p_cntr)
  916. struct cntr_struct *p_cntr;
  917. {
  918.     int count = 0;
  919.  
  920.     while (p_cntr) {
  921.     count++;
  922.     p_cntr = p_cntr -> next;
  923.     }
  924.     return count;
  925. }
  926.  
  927. /*
  928.  * Interpolate given point list (defined via p_cntr) using Complete
  929.  * Spline interpolation.
  930.  */
  931. static complete_spline_interp(p_cntr, n, t_min, t_max, tx1, ty1, tx2, ty2)
  932. struct cntr_struct *p_cntr;
  933. int n;
  934. double t_min, t_max, tx1, ty1, tx2, ty2;
  935. {
  936.     double dt, *tangents_x, *tangents_y;
  937.     int i;
  938.  
  939.     tangents_x = (double *) alloc((unsigned long) (sizeof(double) * n),
  940.                         "contour c_s_intr");
  941.     tangents_y = (double *) alloc((unsigned long) (sizeof(double) * n),
  942.                         "contour c_s_intr");
  943.  
  944.     if (n > 1) prepare_spline_interp(tangents_x, tangents_y, p_cntr, n,
  945.                     t_min, t_max, tx1, ty1, tx2, ty2);
  946.     else {
  947.     free((char *) tangents_x);
  948.     free((char *) tangents_y);
  949.     return(0);
  950.     }
  951.  
  952.     dt = (t_max-t_min)/(n-1);
  953.  
  954.     add_cntr_point(p_cntr -> X, p_cntr -> Y);           /* First point. */
  955.  
  956.     for (i=0; i<n-1; i++) {
  957.         hermit_interp(p_cntr -> X, p_cntr -> Y,
  958.                      tangents_x[i], tangents_y[i],
  959.              p_cntr -> next -> X, p_cntr -> next -> Y,
  960.                      tangents_x[i+1], tangents_y[i+1], dt);
  961.  
  962.         p_cntr = p_cntr -> next;
  963.     }
  964.  
  965.     free((char *) tangents_x);
  966.     free((char *) tangents_y);
  967. }
  968.  
  969. /*
  970.  * Routine to calculate intermidiate value of the Hermit Blending function:
  971.  * This routine should be called only ONCE at the beginning of the program.
  972.  */
  973. static calc_hermit_table()
  974. {
  975.     int i;
  976.     double t, dt;
  977.  
  978.     hermit_table = (table_entry *) alloc ((unsigned long) (sizeof(table_entry) *
  979.                         (num_approx_pts + 1)),
  980.                         "contour hermit table");
  981.     t = 0;
  982.     dt = 1.0/num_approx_pts;
  983.     for (i=0; i<=num_approx_pts; i++) {
  984.         hermit_table[i][0] = (t-1)*(t-1)*(2*t+1);             /* h00. */
  985.         hermit_table[i][1] = t*t*(-2*t+3);                 /* h10. */
  986.         hermit_table[i][2] = t*(t-1)*(t-1);                 /* h01. */
  987.         hermit_table[i][3] = t*t*(t-1);                     /* h11. */
  988.         t = t + dt;
  989.     }
  990. }
  991.  
  992. /*
  993.  * Routine to generate an hermit interpolation between two points given as
  994.  * two InterpStruct structures. Assume hermit_table is already calculated.
  995.  * Currently the points generated are printed to stdout as two reals (X, Y).
  996.  */
  997. static hermit_interp(x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt)
  998. double x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt;
  999. {
  1000.     int i;
  1001.     double x, y, vec_size, tang_size;
  1002.  
  1003.     tx1 *= dt;  ty1 *= dt; /* Normalize the tangents according to param. t.  */
  1004.     tx2 *= dt;  ty2 *= dt;
  1005.  
  1006.     /* Normalize the tangents so that their magnitude will be 1/3 of the     */
  1007.     /* segment length. This tumb rule guaranteed no cusps or loops!          */
  1008.     /* Note that this normalization keeps continuity to be G1 (but not C1).  */
  1009.     vec_size = sqrt(sqr(x1 - x2) + sqr(y2 - y1));
  1010.     tang_size = sqrt(sqr(tx1) + sqr(ty1));                  /* Normalize T1. */
  1011.     if (tang_size * 3 > vec_size) {
  1012.     tx1 *= vec_size / (tang_size * 3);
  1013.     ty1 *= vec_size / (tang_size * 3);
  1014.     }
  1015.     tang_size = sqrt(sqr(tx2) + sqr(ty2));                  /* Normalize T2. */
  1016.     if (tang_size * 3 > vec_size) {
  1017.     tx2 *= vec_size / (tang_size * 3);
  1018.     ty2 *= vec_size / (tang_size * 3);
  1019.     }
  1020.  
  1021.     for (i=1; i<=num_approx_pts; i++) {      /* Note we start from 1 - first */
  1022.         x = hermit_table[i][0] * x1 +       /* point is not printed as it is */
  1023.             hermit_table[i][1] * x2 +   /* redundent (last on last section). */
  1024.             hermit_table[i][2] * tx1 +
  1025.             hermit_table[i][3] * tx2;
  1026.         y = hermit_table[i][0] * y1 +
  1027.             hermit_table[i][1] * y2 +
  1028.             hermit_table[i][2] * ty1 +
  1029.             hermit_table[i][3] * ty2;
  1030.     add_cntr_point(x, y);
  1031.     }
  1032. }
  1033.  
  1034. /*
  1035.  * Routine to Set up the 3*N mat for solve_tri_diag routine used in the
  1036.  * Complete Spline Interpolation. Returns TRUE of calc O.K.
  1037.  * Gets the points list in p_cntr (Of length n) and with tangent vectors tx1,
  1038.  * ty1 at starting point and tx2, ty2 and end point.
  1039.  */
  1040. static prepare_spline_interp(tangents_x, tangents_y, p_cntr, n, t_min, t_max,
  1041.                tx1, ty1, tx2, ty2)
  1042. double tangents_x[], tangents_y[];
  1043. struct cntr_struct *p_cntr;
  1044. int n;
  1045. double t_min, t_max, tx1, ty1, tx2, ty2;
  1046. {
  1047.     int i;
  1048.     double *r, t, dt;
  1049.     tri_diag *m;           /* The tri-diagonal matrix is saved here. */
  1050.     struct cntr_struct *p;
  1051.  
  1052.     m = (tri_diag *) alloc((unsigned long) (sizeof(tri_diag) * n),
  1053.                         "contour tri_diag");
  1054.     r = (double *) alloc((unsigned long) (sizeof(double) * n),
  1055.                         "contour tri_diag2");
  1056.     n--;
  1057.  
  1058.     p = p_cntr;
  1059.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1060.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1061.     r[0] = tx1;                           /* Set start tangent. */
  1062.     r[n] = tx2;                         /* Set end tangent. */
  1063.     t = t_min;
  1064.     dt = (t_max-t_min)/n;
  1065.     for (i=1; i<n; i++) {
  1066.        t = t + dt;
  1067.        m[i][0] = dt;
  1068.        m[i][2] = dt;
  1069.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1070.        r[i] = m[i][0] * ((p -> next -> X) - (p -> X)) / m[i][2]
  1071.             + m[i][2] * ((p -> next -> next -> X) - 
  1072.                          (p -> next -> X)) / m[i][0];
  1073.        r[i] *= 3.0;
  1074.        p = p -> next;
  1075.     }
  1076.  
  1077.     if (!solve_tri_diag(m, r, tangents_x, n+1)) { /* Find the X(t) tangents. */
  1078.         free((char *) m);
  1079.         free((char *) r);
  1080.     int_error("Cannt interpolate X using complete splines", NO_CARET);
  1081.     }
  1082.  
  1083.     p = p_cntr;
  1084.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1085.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1086.     r[0] = ty1;                           /* Set start tangent. */
  1087.     r[n] = ty2;                         /* Set end tangent. */
  1088.     t = t_min;
  1089.     dt = (t_max-t_min)/n;
  1090.     for (i=1; i<n; i++) {
  1091.        t = t + dt;
  1092.        m[i][0] = dt;
  1093.        m[i][2] = dt;
  1094.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1095.        r[i] = m[i][0] * ((p -> next -> Y) - (p -> Y)) / m[i][2]
  1096.             + m[i][2] * ((p -> next -> next -> Y) -
  1097.                          (p -> next -> Y)) / m[i][0];
  1098.        r[i] *= 3.0;
  1099.        p = p -> next;
  1100.     }
  1101.  
  1102.     if (!solve_tri_diag(m, r, tangents_y, n+1)) { /* Find the Y(t) tangents. */
  1103.         free((char *) m);
  1104.         free((char *) r);
  1105.     int_error("Cannt interpolate Y using complete splines", NO_CARET);
  1106.     }
  1107.     free((char *) m);
  1108.     free((char *) r);
  1109. }
  1110.  
  1111. /*
  1112.  * Solve tri diagonal linear system equation. The tri diagonal matrix is
  1113.  * defined via matrix M, right side is r, and solution X i.e. M * X = R.
  1114.  * Size of system given in n. Return TRUE if solution exist.
  1115.  */
  1116. static int solve_tri_diag(m, r, x, n)
  1117. tri_diag m[];
  1118. double r[], x[];
  1119. int n;
  1120. {
  1121.     int i;
  1122.     double t;
  1123.  
  1124.     for (i=1; i<n; i++) {   /* Eliminate element m[i][i-1] (lower diagonal). */
  1125.     if (m[i-1][1] == 0) return FALSE;
  1126.     t = m[i][0] / m[i-1][1];        /* Find ratio between the two lines. */
  1127.     m[i][0] = m[i][0] - m[i-1][1] * t;
  1128.     m[i][1] = m[i][1] - m[i-1][2] * t;
  1129.     r[i] = r[i] - r[i-1] * t;
  1130.     }
  1131.     /* Now do back subtitution - update the solution vector X: */
  1132.     if (m[n-1][1] == 0) return FALSE;
  1133.     x[n-1] = r[n-1] / m[n-1][1];               /* Find last element. */
  1134.     for (i=n-2; i>=0; i--) {
  1135.     if (m[i][1] == 0) return FALSE;
  1136.     x[i] = (r[i] - x[i+1] * m[i][2]) / m[i][1];
  1137.     }
  1138.     return TRUE;
  1139. }
  1140.  
  1141. /*
  1142.  * Generate a Bspline curve defined by all the points given in linked list p:
  1143.  * Algorithm: using deBoor algorithm
  1144.  * Note: if Curvekind is OPEN_CONTOUR than Open end knot vector is assumed,
  1145.  *       else (CLOSED_CONTOUR) Float end knot vector is assumed.
  1146.  * It is assumed that num_of_points is at list 2, and order of Bspline is less
  1147.  * than num_of_points!
  1148.  */
  1149. static gen_bspline_approx(p_cntr, num_of_points, order, contour_kind)
  1150. struct cntr_struct *p_cntr;
  1151. int num_of_points, order, contour_kind;
  1152. {
  1153.     int i, knot_index = 0, pts_count = 1;
  1154.     double dt, t, next_t, t_min, t_max, x, y;
  1155.     struct cntr_struct *pc_temp = p_cntr, *pc_tail;
  1156.  
  1157.     /* If the contour is Closed one we must update few things:               */
  1158.     /* 1. Make the list temporary circular, so we can close the contour.     */
  1159.     /* 2. Update num_of_points - increase it by "order-1" so contour will be */
  1160.     /*    closed. This will evaluate order more sections to close it!        */
  1161.     if (contour_kind == CLOSED_CONTOUR) {
  1162.     pc_tail = p_cntr;
  1163.     while (pc_tail -> next) pc_tail = pc_tail -> next;/* Find last point.*/
  1164.     pc_tail -> next = p_cntr;   /* Close contour list - make it circular.*/
  1165.     num_of_points += order;
  1166.     }
  1167.  
  1168.     /* Find first (t_min) and last (t_max) t value to eval: */
  1169.     t = t_min = fetch_knot(contour_kind, num_of_points, order, order);
  1170.     t_max = fetch_knot(contour_kind, num_of_points, order, num_of_points);
  1171.     next_t = t_min + 1.0;
  1172.     knot_index = order;
  1173.     dt = 1.0/num_approx_pts;            /* Number of points per one section. */
  1174.  
  1175.  
  1176.     while (t<t_max) {
  1177.     if (t > next_t) {
  1178.         pc_temp = pc_temp -> next;     /* Next order ctrl. pt. to blend. */
  1179.             knot_index++;
  1180.         next_t += 1.0;
  1181.     }
  1182.         eval_bspline(t, pc_temp, num_of_points, order, knot_index,
  1183.                         contour_kind, &x, &y);   /* Next pt. */
  1184.     add_cntr_point(x, y);
  1185.     pts_count++;
  1186.     /* As we might have some real number round off problems we must      */
  1187.     /* test if we dont produce too many points here...                   */
  1188.     if (pts_count + 1 == num_approx_pts * (num_of_points - order) + 1)
  1189.             break;
  1190.         t += dt;
  1191.     }
  1192.  
  1193.     eval_bspline(t_max - EPSILON, pc_temp, num_of_points, order, knot_index,
  1194.         contour_kind, &x, &y);
  1195.     /* If from round off errors we need more than one last point: */
  1196.     for (i=pts_count; i<num_approx_pts * (num_of_points - order) + 1; i++)
  1197.     add_cntr_point(x, y);                /* Complete the contour. */
  1198.  
  1199.     if (contour_kind == CLOSED_CONTOUR)     /* Update list - un-circular it. */
  1200.     pc_tail -> next = NULL;
  1201. }
  1202.  
  1203. /*
  1204.  * The recursive routine to evaluate the B-spline value at point t using
  1205.  * knot vector PKList, and the control points Pdtemp. Returns x, y after the
  1206.  * division by the weight w. Note that Pdtemp points on the first control
  1207.  * point to blend with. The B-spline is of order order.
  1208.  */
  1209. static eval_bspline(t, p_cntr, num_of_points, order, j, contour_kind, x, y)
  1210. double t;
  1211. struct cntr_struct *p_cntr;
  1212. int num_of_points, order, j, contour_kind;
  1213. double *x, *y;
  1214. {
  1215.     int i, p;
  1216.     double ti, tikp, *dx, *dy;      /* Copy p_cntr into it to make it faster. */
  1217.  
  1218.     dx = (double *) alloc((unsigned long) (sizeof(double) * (order + j)),
  1219.                         "contour b_spline");
  1220.     dy = (double *) alloc((unsigned long) (sizeof(double) * (order + j)),
  1221.                         "contour b_spline");
  1222.     /* Set the dx/dy - [0] iteration step, control points (p==0 iterat.): */
  1223.     for (i=j-order; i<=j; i++) {
  1224.         dx[i] = p_cntr -> X;
  1225.         dy[i] = p_cntr -> Y;
  1226.         p_cntr = p_cntr -> next;
  1227.     }
  1228.  
  1229.     for (p=1; p<=order; p++) {        /* Iteration (b-spline level) counter. */
  1230.     for (i=j; i>=j-order+p; i--) {           /* Control points indexing. */
  1231.             ti = fetch_knot(contour_kind, num_of_points, order, i);
  1232.             tikp = fetch_knot(contour_kind, num_of_points, order, i+order+1-p);
  1233.         if (ti == tikp) {   /* Should not be a problems but how knows... */
  1234.         }
  1235.         else {
  1236.         dx[i] = dx[i] * (t - ti)/(tikp-ti) +         /* Calculate x. */
  1237.             dx[i-1] * (tikp-t)/(tikp-ti);
  1238.         dy[i] = dy[i] * (t - ti)/(tikp-ti) +         /* Calculate y. */
  1239.             dy[i-1] * (tikp-t)/(tikp-ti);
  1240.         }
  1241.     }
  1242.     }
  1243.     *x = dx[j]; *y = dy[j];
  1244.     free((char *) dx);
  1245.     free((char *) dy);
  1246. }
  1247.  
  1248. /*
  1249.  * Routine to get the i knot from uniform knot vector. The knot vector
  1250.  * might be float (Knot(i) = i) or open (where the first and last "order"
  1251.  * knots are equal). contour_kind determines knot kind - OPEN_CONTOUR means
  1252.  * open knot vector, and CLOSED_CONTOUR selects float knot vector.
  1253.  * Note the knot vector is not exist and this routine simulates it existance
  1254.  * Also note the indexes for the knot vector starts from 0.
  1255.  */
  1256. static double fetch_knot(contour_kind, num_of_points, order, i)
  1257. int contour_kind, num_of_points, order, i;
  1258. {
  1259.     switch (contour_kind) {
  1260.     case OPEN_CONTOUR:
  1261.         if (i <= order) return 0.0;
  1262.         else if (i <= num_of_points) return (double) (i - order);
  1263.          else return (double) (num_of_points - order);
  1264.     case CLOSED_CONTOUR:
  1265.         return (double) i;
  1266.     default: /* Should never happen */
  1267.         return 1.0;
  1268.     }
  1269. #ifdef sequent
  1270.     return 1.0;
  1271. #endif
  1272. }
  1273.